<?php

	class Timing {

		private static $times = array();

		// Set start time
		public static function start($name) {
			$time = array(
				"name"=>$name,
				"start"=>microtime(true),
				"stop"=>microtime(true)
			);
			Timing::$times[$name] = $time;
		}

		// Set stop/end time
		public static function stop($name) {
			Timing::$times[$name]["stop"] = microtime(true);
		}

		// Calculate specific time
		public static function calculate($name) {
			Timing::$times[$name]["time"] = Timing::$times[$name]["stop"] - Timing::$times[$name]["start"];
			return Timing::$times[$name]; 
		}

		// Calculate all times
		public static function calculates() {
			foreach(Timing::$times as $name => $time ){
				Timing::$times[$name]["time"] = Timing::$times[$name]["stop"] - Timing::$times[$name]["start"];
			}
			return Timing::$times;
		}
		
		public static function callbackTimeProcess($name,$callback=array()){
			if(is_array($callback)&&!empty($callback)){
				Timing::start($name);
				Timing::$times[$name]["Callback"]=$callback;
				call_user_func($callback);
				Timing::stop($name);
			}
		}

		public function printMeHide(){
			$filename = REAL_PATH."data/statistic/current".date("Ymd");
			if(file_exists($filename)?true:fclose(fopen($filename,"a"))){
				file_put_contents($filename, "==========> " .date("Y-m-d h:i:s")." <==========\n".print_r(Timing::calculates(), TRUE) , FILE_APPEND | LOCK_EX);
			}
		}
		
		public function saveStatistic(){
			$filename = REAL_PATH."data/statistic/".date("Ymd");
			if(file_exists($filename)?true:fclose(fopen($filename,"a"))){
				file_put_contents($filename, json_encode(Timing::calculates()) . ";" , FILE_APPEND | LOCK_EX);
			}
		}
		
	}